package com.university.mentalhealthplatform.studentV3.ai.session;


import com.university.mentalhealthplatform.global.rbac.jwt.JwtUtils;
import com.university.mentalhealthplatform.studentV3.ai.message.AiMessage;
import com.university.mentalhealthplatform.studentV3.ai.message.AiMessageDTO;
import io.qifan.infrastructure.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("api/v3/session")
@RestController
@AllArgsConstructor
public class AiSessionController {
    private final AiSessionRepository sessionRepository;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private HttpServletRequest request;

    @GetMapping("{id}")
    public AiSessionDTO findById(@PathVariable String id) {
        AiSession session = sessionRepository.findById(id).orElseThrow(() -> new BusinessException("会话不存在"));
        return toDTO(session);
    }

    @PostMapping("save")
    public String save(@RequestBody AiSessionInput input) {
        String loginId = getLoginIdFromToken();
        AiSession session = input.toEntity();
        session.setCreatorId(loginId);
        session.setEditorId(loginId);
        session.setCreatedTime(LocalDateTime.now());
        session.setEditedTime(LocalDateTime.now());
        session.setName(input.getName());
        return sessionRepository.save(session).getId();
    }

    @GetMapping("user")
    public List<AiSessionDTO> findByUser() {
        String loginId = getLoginIdFromToken();
        List<AiSession> sessions = sessionRepository.findByCreatorId(loginId);
        return sessions.stream().map(this::toDTO).collect(Collectors.toList());
    }

    @DeleteMapping
    public void delete(@RequestBody List<String> ids) {
        sessionRepository.deleteAllById(ids);
    }

    private AiSessionDTO toDTO(AiSession session) {
        AiSessionDTO dto = new AiSessionDTO();
        dto.setId(session.getId());
        dto.setCreatedTime(session.getCreatedTime());
        dto.setEditedTime(session.getEditedTime());
        dto.setCreatorId(session.getCreatorId());
        dto.setEditorId(session.getEditorId());
        dto.setName(session.getName());
        dto.setMessages(session.getMessages().stream().map(this::toMessageDTO).collect(Collectors.toList()));
        return dto;
    }

    private AiMessageDTO toMessageDTO(AiMessage message) {
        AiMessageDTO dto = new AiMessageDTO();
        dto.setId(message.getId());
        dto.setCreatedTime(message.getCreatedTime());
        dto.setEditedTime(message.getEditedTime());
        dto.setCreatorId(message.getCreatorId());
        dto.setEditorId(message.getEditorId());
        dto.setType(message.getType());
        dto.setTextContent(message.getTextContent());
        dto.setSessionId(message.getSession().getId());
        return dto;
    }

    private String getLoginIdFromToken() {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.extractUsername(token);
        }
        throw new BusinessException("无效的Token");
    }
}